package com.hs.telepass.controller;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import com.hs.telepass.controller.task.Task;
import com.hs.telepass.utils.LogUtil;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TaskQueue extends IntentService {
    private static final int NUMBER_OF_CORES; // CPU个数
    private static final int MAXIMUM_POOL_SIZE; // 线程池最大值

    private static ExecutorService cachedThreadPool;
    private static int runningCount = 0;
    private static int runningId = 0;

    static {
        NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
        MAXIMUM_POOL_SIZE = Math.max(NUMBER_OF_CORES, 4);

        cachedThreadPool = Executors.newCachedThreadPool();
    }

    /**
     * 命令进入请求队列，等待onHandleIntent执行
     */
    public static void enqueue(final Context context, final Task task) {
//		Intent intent = new Intent(context, TaskQueue.class);
//		intent.putExtra("task", task);
//		context.startService(intent);

        final int currentRunningId = ++runningId;
        cachedThreadPool.execute(new Runnable() {
            @Override
            public void run() {
                runningCount++;
                LogUtil.w("runningId=" + currentRunningId + ", countOfRunning=" + runningCount + ", Begin");
                task.execute(context, task);
                LogUtil.w("runningId=" + currentRunningId + ", countOfRunning=" + runningCount + ", End");
                runningCount--;
            }
        });
    }


    public TaskQueue() {
        super("TaskQueue");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    protected void onHandleIntent(final Intent intent) {
        Task task = (Task) intent.getSerializableExtra("task");
        task.execute(TaskQueue.this, task);
    }
}